package com.xtayfjpk.zookeeper.test.master_workers.callback.worker;

import java.util.List;

import org.apache.log4j.Logger;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.Code;

import com.xtayfjpk.zookeeper.test.master_workers.Worker;
import com.xtayfjpk.zookeeper.test.master_workers.callback.BaseChildrenCallback;

public class WorkerTasksGetChildrenCallback extends BaseChildrenCallback {
	private static final Logger LOGGER = Logger.getLogger(WorkerTasksGetChildrenCallback.class);
	private Worker worker;
	
	public WorkerTasksGetChildrenCallback(Worker worker) {
		this.worker = worker;
	}
	
	@Override
	protected void connectionLossCaseAction(int rc, String path, Object ctx,
			List<String> children) {
		worker.monitorTasks();
	}
	
	@Override
	protected void okCaseAction(int rc, String path, Object ctx, final List<String> children) {
		if(children!=null) {
			worker.getExecutor().execute(new Runnable() {
				@Override
				public void run() {
					LOGGER.info("Looping into tasks");
					worker.setStatus("Working");
					for(String task : children) {
						LOGGER.info("New task: " + task);
						worker.getNewTaskData(task);
					}
					
				}
			});
		}
	}
	
	@Override
	protected void defaultCaseAction(int rc, String path, Object ctx, List<String> children) {
		LOGGER.info("getChildren failed: " + KeeperException.create(Code.get(rc), path));
	}
}
